const adminModel = require('../models/admin');
const orderModel = require('../models/order');
const goodsModel = require('../models/goods');
const userModel = require('../models/user');
const userProfileModel = require('../models/user_profile');
const { generateToken } = require('../utils/auth');
const { pool } = require('../config/db');
const upload = require('../config/upload');

// 管理员登录
exports.login = async (req, res) => {
  try {
    const { username, password } = req.body;
    
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        message: '用户名和密码不能为空'
      });
    }
    
    // 验证管理员登录
    const result = await adminModel.verifyAdminLogin(username, password);
    
    if (!result.success) {
      return res.status(401).json({
        success: false,
        message: result.message
      });
    }
    
    // 生成token
    const token = generateToken(result.user.id, 'admin');
    
    res.json({
      success: true,
      token,
      data: {
        adminInfo: result.user
      },
      message: '登录成功'
    });
  } catch (error) {
    console.error('管理员登录失败:', error);
    res.status(500).json({
      success: false,
      message: '登录失败，请稍后重试'
    });
  }
};

// 获取所有订单列表
exports.getOrders = async (req, res) => {
  try {
    // 确保分页参数是整数类型
    const { status, keyword } = req.query;
    // 确保page和pageSize是有效的数字类型，避免NaN
    const page = Number.isInteger(Number(req.query.page)) ? Number(req.query.page) : 1;
    const pageSize = Number.isInteger(Number(req.query.pageSize)) ? Number(req.query.pageSize) : 10;
    
    // 构建查询条件
  let query = 'SELECT * FROM orders WHERE 1=1';
  
  if (status) {
    query += ` AND status = '${status}'`;
  }
  
  if (keyword) {
    // 同时搜索商品信息和订单编号
    query += ' AND (';
    
    // 1. 搜索商品信息中的标题等字段
    query += ` goods_info LIKE '%${keyword}%'`;
    
    // 2. 尝试从关键词中提取订单编号中的ID部分进行搜索
    // 订单编号格式为: ORD00000001
    const idMatch = keyword.match(/ORD(\d+)/i);
    if (idMatch && idMatch[1]) {
      const orderId = parseInt(idMatch[1]);
      if (!isNaN(orderId)) {
        query += ` OR id = ${orderId}`;
      }
    }
    
    // 3. 如果关键词是纯数字，也尝试直接匹配订单ID
    const numericId = parseInt(keyword);
    if (!isNaN(numericId) && String(numericId) === keyword) {
      query += ` OR id = ${numericId}`;
    }
    
    query += ')';
  }
  
  // 添加排序和分页
  query += ' ORDER BY created_at DESC';
  
  // 获取总条数
  const countQuery = query.replace('SELECT *', 'SELECT COUNT(*) as count');
  const [countResult] = await pool.execute(countQuery);
  const total = countResult[0].count;
  
  // 添加分页
  const startIndex = (page - 1) * pageSize;
  query += ` LIMIT ${startIndex}, ${pageSize}`;
  
  // 执行查询
  const [orders] = await pool.execute(query);
    
    // 获取订单关联的用户信息
    for (let i = 0; i < orders.length; i++) {
      // 为订单添加order_no字段，使用id生成订单编号
      orders[i].order_no = `ORD${String(orders[i].id).padStart(8, '0')}`;
      const user = await userModel.findUserById(orders[i].user_id);
      const userProfile = await userProfileModel.getUserProfileByUserId(orders[i].user_id);
      
      if (user) {
        orders[i].user_info = {
          openid: user.openid,
          nickName: userProfile?.nickName || user.nickname,
          avatarUrl: userProfile?.avatarUrl || user.avatar
        };
      }
      
      // 解析goods_info JSON
      if (orders[i].goods_info) {
        try {
          // 检查goods_info是否已经是对象，如果不是才进行解析
          if (typeof orders[i].goods_info === 'string') {
            orders[i].goods_info = JSON.parse(orders[i].goods_info);
          }
        } catch (error) {
          console.warn('解析商品信息失败:', error);
        }
      }
    }
    
    res.json({
      success: true,
      data: {
        orders,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      },
      message: '获取订单列表成功'
    });
  } catch (error) {
    console.error('获取订单列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单列表失败，请稍后重试'
    });
  }
};

// 获取订单详情
exports.getOrderDetail = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 获取订单信息
    const order = await orderModel.getOrderById(parseInt(id));
    
    if (!order) {
      return res.status(404).json({
        success: false,
        message: '订单不存在'
      });
    }
    
    // 获取用户信息
    const user = await userModel.findUserById(order.user_id);
    const userProfile = await userProfileModel.getUserProfileByUserId(order.user_id);
    
    if (user) {
      order.user_info = {
        openid: user.openid,
        nickName: userProfile?.nickName || user.nickname,
        avatarUrl: userProfile?.avatarUrl || user.avatar
      };
    }
    
    // 解析goods_info JSON
    if (order.goods_info) {
      try {
        // 检查goods_info是否已经是对象，如果不是才进行解析
        if (typeof order.goods_info === 'string') {
          order.goods_info = JSON.parse(order.goods_info);
        }
      } catch (error) {
        console.warn('解析商品信息失败:', error);
      }
    }
    
    res.json({
      success: true,
      data: order,
      message: '获取订单详情成功'
    });
  } catch (error) {
    console.error('获取订单详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取订单详情失败，请稍后重试'
    });
  }
};

// 更新订单状态
exports.updateOrderStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;
    
    if (!status) {
      return res.status(400).json({
        success: false,
        message: '缺少订单状态'
      });
    }
    
    // 更新订单状态
    const updatedOrder = await orderModel.updateOrderStatus(parseInt(id), status);
    
    res.json({
      success: true,
      data: updatedOrder,
      message: '更新订单状态成功'
    });
  } catch (error) {
    console.error('更新订单状态失败:', error);
    res.status(500).json({
      success: false,
      message: '更新订单状态失败，请稍后重试'
    });
  }
};

// 获取商品列表
exports.getGoodsList = async (req, res) => {
  try {
    const { keyword } = req.query;
    // 确保分页参数是整数类型
    const page = parseInt(req.query.page || 1);
    const pageSize = parseInt(req.query.pageSize || 10);
    
    // 调用现有商品模型的方法获取商品列表
    const goodsList = await goodsModel.getGoodsList(page, pageSize);
    
    // 获取总条数
    const countQuery = 'SELECT COUNT(*) as count FROM goods';
    const [countResult] = await pool.execute(countQuery);
    const total = countResult[0].count;
    
    res.json({
      success: true,
      data: {
        goods: goodsList,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      },
      message: '获取商品列表成功'
    });
  } catch (error) {
    console.error('获取商品列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取商品列表失败，请稍后重试'
    });
  }
};

// 获取商品详情
exports.getGoodsDetail = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 调用现有商品模型的方法获取商品详情
    const goods = await goodsModel.getGoodsById(parseInt(id));
    
    if (!goods) {
      return res.status(404).json({
        success: false,
        message: '商品不存在'
      });
    }
    
    res.json({
      success: true,
      data: goods,
      message: '获取商品详情成功'
    });
  } catch (error) {
    console.error('获取商品详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取商品详情失败，请稍后重试'
    });
  }
};

// 创建商品 - 带图片上传
// 注意：这个函数本身不直接导出，而是通过下面的中间件包装函数导出
const createGoodsHandler = async (req, res) => {
  try {
    const goodsData = req.body;
    
    // 解析规格参数
    if (goodsData.specifications && typeof goodsData.specifications === 'string') {
      try {
        goodsData.specifications = JSON.parse(goodsData.specifications);
      } catch (error) {
        console.warn('解析规格参数失败，使用空数组:', error);
        goodsData.specifications = [];
      }
    }
    
    // 如果有上传的图片，更新商品数据中的image字段
    if (req.file) {
      // 保存图片的相对路径
      goodsData.image = '/uploads/' + req.file.filename;
    }
    
    // 调用现有商品模型的方法创建商品
    const goods = await goodsModel.createGoods(goodsData);
    
    res.json({
      success: true,
      data: goods,
      message: '创建商品成功'
    });
  } catch (error) {
    console.error('创建商品失败:', error);
    res.status(500).json({
      success: false,
      message: '创建商品失败，请稍后重试'
    });
  }
};

// 导出原始处理函数，中间件将在路由中应用
exports.createGoods = createGoodsHandler;

// 更新商品 - 带图片上传
// 注意：这个函数本身不直接导出，而是通过下面的中间件包装函数导出
const updateGoodsHandler = async (req, res) => {
  try {
    const { id } = req.params;
    const goodsData = req.body;
    
    // 解析规格参数
    if (goodsData.specifications && typeof goodsData.specifications === 'string') {
      try {
        goodsData.specifications = JSON.parse(goodsData.specifications);
      } catch (error) {
        console.warn('解析规格参数失败，使用空数组:', error);
        goodsData.specifications = [];
      }
    }
    
    // 如果有上传的图片，更新商品数据中的image字段
    if (req.file) {
      // 保存图片的相对路径
      goodsData.image = '/uploads/' + req.file.filename;
    }
    
    // 调用现有商品模型的方法更新商品
    const goods = await goodsModel.updateGoods(parseInt(id), goodsData);
    
    res.json({
      success: true,
      data: goods,
      message: '更新商品成功'
    });
  } catch (error) {
    console.error('更新商品失败:', error);
    res.status(500).json({
      success: false,
      message: '更新商品失败，请稍后重试'
    });
  }
};

// 导出原始处理函数，中间件将在路由中应用
exports.updateGoods = updateGoodsHandler;

// 删除商品
exports.deleteGoods = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 检查是否有任何订单引用了该商品
    const checkAnyOrderQuery = 'SELECT COUNT(*) as count FROM orders WHERE goods_id = ?';
    const [anyOrderCount] = await pool.execute(checkAnyOrderQuery, [parseInt(id)]);
    
    if (anyOrderCount[0].count > 0) {
      return res.status(400).json({
        success: false,
        message: '该商品存在关联的订单记录，无法删除'
      });
    }
    
    // 调用现有商品模型的方法删除商品
    await goodsModel.deleteGoods(parseInt(id));
    
    res.json({
      success: true,
      message: '删除商品成功'
    });
  } catch (error) {
    console.error('删除商品失败:', error);
    res.status(500).json({
      success: false,
      message: '删除商品失败，请稍后重试'
    });
  }
};

// 获取用户列表
exports.getUsers = async (req, res) => {
  try {
    const { keyword, page = 1, pageSize = 10 } = req.query;
    
    // 构建查询条件
    let query = 'SELECT * FROM users WHERE 1=1';
    const params = [];
    
    if (keyword) {
      query += ' AND (openid LIKE ? OR nickname LIKE ? OR unionid LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`, `%${keyword}%`);
    }
    
    // 添加排序和分页
    query += ' ORDER BY created_at DESC';
    
    // 获取总条数
    const countQuery = query.replace('SELECT *', 'SELECT COUNT(*) as count');
    const [countResult] = await pool.execute(countQuery, params);
    const total = countResult[0].count;
    
    // 添加分页
    const startIndex = (parseInt(page) - 1) * parseInt(pageSize);
    query += ' LIMIT ?, ?';
    params.push(startIndex, parseInt(pageSize));
    
    // 执行查询
    const [users] = await pool.execute(query, params);
    
    // 获取用户的完整信息
    for (let i = 0; i < users.length; i++) {
      const userProfile = await userProfileModel.getUserProfileByUserId(users[i].id);
      
      if (userProfile) {
        users[i].profile = {
          nickName: userProfile.nickName,
          avatarUrl: userProfile.avatarUrl,
          gender: userProfile.gender,
          language: userProfile.language,
          city: userProfile.city,
          province: userProfile.province,
          country: userProfile.country
        };
      }
      
      // 不返回密码
      delete users[i].password;
    }
    
    res.json({
      success: true,
      data: {
        users,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      },
      message: '获取用户列表成功'
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户列表失败，请稍后重试'
    });
  }
};

// 获取用户详情
exports.getUserDetail = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 获取用户基本信息
    const user = await userModel.findUserById(parseInt(id));
    
    if (!user) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }
    
    // 获取用户完整信息
    const userProfile = await userProfileModel.getUserProfileByUserId(parseInt(id));
    
    if (userProfile) {
      user.profile = {
        nickName: userProfile.nickName,
        avatarUrl: userProfile.avatarUrl,
        gender: userProfile.gender,
        language: userProfile.language,
        city: userProfile.city,
        province: userProfile.province,
        country: userProfile.country
      };
    }
    
    // 不返回密码
    delete user.password;
    
    res.json({
      success: true,
      data: user,
      message: '获取用户详情成功'
    });
  } catch (error) {
    console.error('获取用户详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户详情失败，请稍后重试'
    });
  }
};